package org.yagnus.stats.summary.univariate;

import java.util.ArrayList;
import java.util.Collections;

public class Median implements UnivariateSummaryStatistic<Double> {

	ArrayList<Double> values = new ArrayList<Double>();

	public void add(Double v) {
		values.add(v);
	}

	public Double get() {
		double ret = 0;
		int l = values.size();
		if (l == 0) {
			return null;
		} else if (l == 1) {
			ret = values.get(0);
		}

		Collections.sort(values);

		if (l % 2 == 1) {
			l /= 2; // actually (l/2+1 -1) to account for 0-based index
			ret = values.get(l);
		} else {
			l /= 2;
			ret = values.get(l) / 2d + values.get(l + 1) / 2d;
		}

		return ret;
	}

	public void clear() {
		values.clear();
	}

}
